
package cn.zniot.so.transport;

import cn.zniot.so.application.constant.Constants;
import cn.zniot.so.transport.server.BoxAndClientServer;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.filter.codec.ProtocolCodecFactory;

/**
 * 网络模块工厂类
 */
public class NetFacade {

    private static NetFacade instance = new NetFacade();

    private NetFacade() {
    }

    public static NetFacade getInstance() {
        return instance;
    }

    /**
     * 创建TCP服务器
     */
    public IServer createBoxServer(int logicProcessor, int serverPort,
            IoHandler handler) throws Exception {
        IServer server = new BoxAndClientServer(logicProcessor, serverPort);
        server.setProtocolCodec(this.getProtocolCodec());// 指定协议工厂ZniotCodecFactory
        server.setHandler(handler);
        server.init();
        return server;
    }

    /**
     * 实例化协议转换器类
     */
    private ProtocolCodecFactory getProtocolCodec() throws Exception {
        Class<?> clazz = null;
        ProtocolCodecFactory protocolCodec = null;
        try {
            clazz = Class.forName(Constants.CLASSNAME_PROTOCOLCODEC);
            protocolCodec = (ProtocolCodecFactory) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            throw new Exception(e.getMessage(), e);
        } catch (InstantiationException e) {
            throw new Exception("failure instancing protocolCodec. className:"
                    + Constants.CLASSNAME_PROTOCOLCODEC, e);
        } catch (IllegalAccessException e) {
            throw new Exception("failure instancing protocolCodec. className:"
                    + Constants.CLASSNAME_PROTOCOLCODEC, e);
        }
        return protocolCodec;
    }

}
